package com.example.springboottest.example.xml;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Dom4j操作xml
 * 优点：
 * 形成了树结构，直观好理解
 * 解析过程树结构保存在内存中，方便修改
 * 缺点：
 * 当文档较大，容易溢出
 */
public class DomDemo {
    public static final String DEMO_XML_URL = "src/main/java/com/example/springboottest/example/xml/demo.xml";

    //用Element方式
    public static void element(NodeList list) {
        for (int i = 0; i < list.getLength(); i++) {
            Element element = (Element) list.item(i);
            NodeList childNodes = element.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    //获取节点
                    System.out.print(childNodes.item(j).getNodeName() + ":");
                    //获取节点值
                    System.out.print(childNodes.item(j).getFirstChild().getNodeValue());
                }
            }
        }
    }

    public static void node(NodeList list) {
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            NamedNodeMap map = node.getAttributes();
            Node rollnoAttribute = map.getNamedItem("rollno");
            if (rollnoAttribute != null) {
                Node rollnoNode = rollnoAttribute.getFirstChild();
                System.out.print("rollno:" + rollnoNode.getNodeValue() + "\t");
            }
            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    System.out.print(childNodes.item(j).getNodeName() + ":");
                    System.out.print(childNodes.item(j).getFirstChild().getNodeValue() + "\t");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        //1.创建DocumentBuilderFactory对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //2.创建DocumentBuilder对象
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document d = builder.parse(DEMO_XML_URL);
            NodeList sList = d.getElementsByTagName("student");
            //element(sList);
            node(sList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}